<?php

declare(strict_types=1);

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use Hyperf\DbConnection\Db;
use App\Service\Code\Normal;
use App\Service\VendorClient\S2bMoBaoPay\S2bMoBaoPayApiClient;
use Service\AppService\IdService;
use App\Service\OrderService\OrderQueryService\QueryGoodsMicService;
use App\Service\BaseService;
use App\Service\OrderService\OrderInterfaceService\CreateOrder;
use App\Service\OrderService\OrderInterfaceService\OrderAfterSale;
use App\Service\OrderService\OrderInterfaceService\OrderCancel;
use App\Service\VendorClient\OrderDeclareServiceApi\OrderDeclareServiceApiClient;
use App\Service\OrderService\OrderInterfaceService\OrderDeclare;
use App\Service\CommodityService\SupplierCommodityPriceService;

class OrderSupplier extends BasePssModel
{
    public $table = 'order_supplier';
    
    const order_trade_type_normal   = 1;
    const order_trade_type_coupon   = 2;
    const order_trade_type_deposit  = 3;
    const order_trade_type_recharge = 4;
    
    //订单交易模式类型（1-普通订单，2-卡券订单，3-预售订单，4-充值订单）
    public $order_trade_type = [
        self::order_trade_type_normal   => '普通订单',
        self::order_trade_type_coupon   => '卡券订单',
        self::order_trade_type_deposit  => '预售订单',
        self::order_trade_type_recharge => '充值订单'
    ];
    
    //订单支付状态
    public $order_status = [
        '0'     => '待支付',
        '1'     => '已支付',
        '2'     => '已发货',
        '100'   => '已取消',
        '200'   => '支付失败',
    ];
    
    //订单推送状态
    public $order_push_status = [
        '0'     => '未推送',
        '1'     => '推送成功',
        '2'     => '推送失败',
    ];
    
    //支付方式
    public $pay_way = [
        '1' => [
            'client_name' => '摩宝支付',
            'client'    => "App\\Service\\VendorClient\\S2bMoBaoPay\\S2bMoBaoPayApiClient"
        ],
        '2' => [
            'client_name' => "块钱支付",
            'client'    => ""
        ],
        '3' => [
            'client_name' => '通联支付',
            'client'    => "App\\Service\\VendorClient\\AlinpayApi\\AlinOnlineScanPayApiClient"
        ],
        '4' => [
            'client_name' => '新生支付',
            'client'    => "App\\Service\\VendorClient\\HnPay\\HnPayClient"
        ],
        '5' => [
            'client_name' => '易生支付',
            'client'    => "App\\Service\\VendorClient\\EasyPayApi\\EasyPayApiClient"
        ]

    ];
    
    //订单审核状态
    public $after_verify_status = [
        '0'     => '待审核',
        '1'     => '审核通过',
        '2'     => '审核拒绝',
    ];
    
    public $order_fields = [
        'id',
        'bid',
        'order_type',
        'order_trade_type',
        'order_sn',
        'order_status',
        'order_push_status',
        'is_apply',
        'apply_time',
        'order_type',
        'store_id',
        'supplier_psn',
        'supplier_csn',
        'supplier_dsn',
        'thirdpart_order_sn',
        'thirdpart_user_order_sn',
        'company_id',
        'after_sale_async_sn',
        'after_sale_async_status',
        'order_money',
        'real_total_money',
        'deliver_money',
        'goods_money',
        'discount_money',
        'real_total_money',
        'settlement_total_money',
        'total_template_delivery',
        'costprice',
        'buyer_realname',
        'buyer_phone',
        'buyer_idcard',
        'receive_name',
        'recveive_phone',
        'province',
        'city',
        'district',
        'receive_address',
        'order_source',
        'apply_remark',
        'apply_extends',
        'pay_time',
        'pay_sn',
        'order_remark',
        'express_name',
        'express_sn',
        'express_shipping_time',
        'tax',
        'is_order_declare',
        'is_pay_declare',
        'apply_request',
        'apply_response',
        'is_channel_settlement',
        'is_supplier_settlement',
        'is_top_system',
        'after_supplier_notify_status',
        'after_supplier_notify_remark',
        'after_channel_notify_status',
        'after_channel_notify_remark',
        'cd'
    ];

    /**
     * 获取订单物流信息组
     * @param number $bid
     * @param string $orderSn
     */
    public function getUserSupplierOrderExpressByBidAndOrderSn( $bid = 0 ,$orderSn = NULL )
    {
        return self::query()
            ->where([
                ['bid','=',$bid],
                ['order_sn','=',$orderSn],
                ['order_status','=',2]
            ])
            ->select([
                Db::raw('order_sn as orderSn'),
                Db::raw('supplier_psn AS orderNo'),
                Db::raw('supplier_csn AS hnOrderNo'),
                Db::raw('express_sn AS expressSn'),
                Db::raw('express_code AS expressCode'),
                Db::raw('express_name AS expressName'),
                Db::raw('express_shipping_time as deliveryTime')
            ])
            ->get()
            ->toArray();
    }

    /**
     * 获取商户订单分组列表
     * @param array $param
     */
    public function orderSupplierList( $param = [] )
    {
        $page_data = $this->getUserOrderPageList($param);
        $orderList = [];
        if( !empty($page_data['data']) )
        {
            $orderList = $page_data['data'];
            $orderSns  = array_column($orderList,'order_sn');
            $orderSupplierList = $this->getSupplierOrderList($orderSns);

            //获取供应商订单商品
            $orderIds = array_column($orderSupplierList, 'order_id');
            $orderGoodsList = OrderSupplierGoods::instance()->getSupplierOrderGoodsByOrderIds($orderIds);

            //处理子订单商品数据
            $orderGoodsListNew = [];
            foreach ($orderGoodsList as $item )
            {
                $price = (string)$item['price'];
                $quantity = (string)$item['quantity'];
                $goods_money = bcmul($price, $quantity,2);
                $item['goods_money']       = number_format((float)$goods_money,2);
                $item['tax']               = number_format((float)$item['tax'],2);
                $imageArr = \explode(",",$item['image']);
                $item['image'] = $imageArr[0]??'';
                $orderGoodsListNew[$item['order_id']][] = $item;
            }

            //重组供应商订单
            $orderSupplier = [];
            foreach ($orderSupplierList as & $item )  {
                $item['order_status_name']  = $this->order_status[$item['order_status']] ??'';
                $item['after_sale_time']    = $item['after_sale_status'] == 1 ? date('Y-m-d H:i:s',$item['after_sale_time']) : '';
                $item['after_verify_time']  = !empty($item['after_verify_time']) ? date("Y-m-d H:i:s",$item['after_verify_time']) : '';
                $item['orderGoodsList']     = $orderGoodsListNew[$item['order_id']];
                $item['order_create_time']  = !empty($item['order_create_time']) ? date("Y-m-d H:i:s",$item['order_create_time']) : '';
                $item['orderGoodsList']     = $orderGoodsListNew[$item['order_id']];
                $orderSupplier[$item['order_sn']][] = $item;
                unset($item);
            }

            foreach ($orderList as $key => & $item ) {
                $childOrderList = $orderSupplier[$item['order_sn']];
                $item['order_list'] = $childOrderList;
            }
        }
        $page_data['data'] = $orderList;
        return Normal::returnCode(Normal::SUC,"获取成功",$page_data);
    }

    /**
     * 获取供应商订单商品信息
     * @param array $orderSns
     */
    public function getSupplierOrderList( $orderSns = [] )
    {
        return self::query()
            ->select([
                DB::raw("concat(id,'') as order_id"),
                DB::raw("concat(company_id,'') as company_id"),
                DB::raw("concat(store_id,'') as store_id"),
                DB::raw("real_total_money as pay_money"),
                DB::raw("cd as order_create_time"),
                "order_sn",
                "supplier_dsn",
                "order_status",
                "pay_status",
                "after_sale_status",
                "after_sale_status",
                "after_sale_time",
                "after_verify_status",
                "after_verify_remark",
                "after_verify_time",
                "deliver_money"
            ])
            ->whereIn('order_sn',$orderSns)
            ->get()
            ->toArray();
    }

    /**
     * 获取订单主表数据
     * @param array $param
     */
    public function getUserOrderPageList( $param = [] )
    {
        $body = $param['body'];
        $page = isset($body['page']) ? $body['page'] : 1 ;
        $columns = [
            Db::raw("DISTINCT order_sn"),
        ];
        $query = self::query();
        $query = $this->getWhereParam($query,$param);
        return $query->orderBy("cd","desc")->paginate(10, $columns, 'page', $page,true)->toArray();
    }

    /**
     * 构建公共参数
     */
    public function getWhereParam($query,$parameter)
    {
        $body = $parameter['body'];
        $bid = $parameter['binfo']['bid'];
        $query->where("bid",$bid);

        //搜索订单号
        if( !empty($body['order_sn']) ) {
            $order_sn = checkFields($body['order_sn']);
            $query->where("order_sn",$order_sn);
        }

        //售后状态
        if( isset($body['after_sale_status']) && in_array($body['after_sale_status'],['0','1']) ) {
            $after_sale_status = checkFields($body['after_sale_status']);
            $after_sale_status = intval($after_sale_status);
            $query->where(function( $query ) use ($after_sale_status) {
                if( $after_sale_status == 1 ) {
                    $query->where(function( $query ) {
                        $query->where("order_type",0)->where('after_sale_status',1);
                    });
                    $query->orWhere(function( $query ) {
                        $query->whereIn("order_type",[1,2])->where('after_sale_status',1)->where('after_verify_status',1);
                    });
                } else {
                    $query->where(function( $query ) {
                        $query->where('after_sale_status',0);
                    });
                }
            });
        }

        //订单时间
        $order_start_time   = isset($body['order_start_time']) ? strtotime($body['order_start_time']) : 0 ;
        $order_end_time     = isset($body['order_end_time']) ? strtotime($body['order_end_time']) : 0 ;
        $order_end_time   = $order_end_time ? ($order_end_time + 86399) : 0 ;
        if( !empty($order_start_time) && !empty($order_end_time) ) {
            $query->where("cd",">=",$order_start_time)->where("cd","<=",$order_end_time);
        } else if( !empty($order_start_time) ) {
            $query->where("cd",">=",$order_start_time);
        } else if( !empty($order_end_time) ) {
            $query->where("cd","<=",$order_end_time);
        }

        //订单状态
        if( isset($body['order_status']) && in_array($body['order_status'],['0','1','2']) ) {
            $order_status = checkFields($body['order_status']);
            $order_status = intval($order_status);
            $query->where("order_status","=",$order_status);
        }

        return $query;
    }

    /**
     * 订单详情接口
     * @param array $param
     */
    public function orderInfo( $param = [])
    {
        $body = $param['body'];
        if( empty($body['order_id']) ) {
            return Normal::returnCode(Normal::FAIL,"except param order_id");
        }
        $order_id = $body['order_id'];
        $orderInfo = $this->info(['id'=>$order_id],[
            'bid',
            'order_sn',
            'supplier_dsn',
            'order_money',
            'order_status',
            'order_remark',
            'pay_money',
            'pay_sn',
            'pay_status',
            'pay_time',
            'pay_remark',
            'cancel_remark',
            'goods_money',
            'deliver_money',
            'discount_money',
            'total_money',
            'invoice_money',
            'real_total_money',
            'tax',
            'buyer_realname',
            'buyer_phone',
            'buyer_idcard',
            'receive_name',
            'recveive_phone',
            'province',
            'city',
            'district',
            'receive_address',
            'express_sn',
            'express_code',
            'express_name',
            'express_shipping_time',
            'company_id',
            'after_sale_status',
            'after_sale_remark',
            'after_sale_time',
            'after_verify_status',
            'after_verify_remark',
            'after_verify_time'
        ]);

        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单数据不能为空");
        }

        //更新详细地址
        $orderInfo['receive_address'] = implode(" ", [
            $orderInfo['province'],
            $orderInfo['city'],
            $orderInfo['district'],
            $orderInfo['receive_address'],
        ]);

        $orderGoods = OrderSupplierGoods::instance()->rows(['order_id' => $order_id],[
            "barcode",
            Db::raw("goods_name AS goodsName"),
            "goods_type",
            "image",
            "barcode",
            "skucode",
            Db::raw("supplier_skucode as supplierSkucode"),
            "price",
            "quantity",
            "batch_no",
            Db::raw("spec_num AS specNum"),
            Db::raw("total as totalPrice"),
            "tax",
            "tax_rate"
        ]);

        if( empty($orderGoods) ) {
            return Normal::returnCode(Normal::FAIL,"获取订单数据失败");
        }
        $orderGoods = array_map(function( & $value ) {
            $imageArr = \explode(",",$value['image']);
            $value['image'] = $imageArr[0]??'';
            $goods_type = [
                '0' => '一般贸易',
                '1' => '保税商品',
                '2' => '海外直邮'
            ];
            $value['goods_type_name'] = $goods_type[$value['goods_type']]??'未定义';
            return $value;
        }, $orderGoods);
        $orderInfo['orderStatusName'] =$this->order_status[$orderInfo['order_status']]??'未定义';
        $orderInfo['pay_time'] = !empty($orderInfo['pay_time']) ? date('Y-m-d H:i:s',$orderInfo['pay_time']) :"" ;
        $orderInfo['express_shipping_time'] = !empty($orderInfo['express_shipping_time']) ? date("Y-m-d H:i:s",$orderInfo['express_shipping_time']) : '';
        $orderInfo['orderGoodsList']  = $orderGoods;

        $tax_all=0;
        foreach ($orderGoods as $item){
            $tax_rate       = bcadd('1', (string)$item['tax_rate'],4);
            $singleTax      = bcdiv((string)$item['price'],$tax_rate,2);
            $singleTax      = bcsub((string)$item['price'],$singleTax,2);
            $singleTaxAll   = bcmul($singleTax,(string)$item['quantity'],2);
            $tax_all        = bcadd((string)$tax_all,$singleTaxAll,2);
        }
        $orderInfo['taxAll']=$tax_all;
        return Normal::returnCode(Normal::SUC,"获取成功",$orderInfo);
    }

    /**
     * 获取订单预支付接口支付信息
     * @param array $param
     */
    public function orderPrePayInfo( $param = [] )
    {
        $body   = $param['body'];
        $binfo  = $param['binfo'];
        if( empty($body['order_sn']) ) {
            return Normal::returnCode(Normal::FAIL,"except param order_sn");
        }

        //查询订单是否支付
        $order_sn = $body['order_sn'];
        $orderInfo = OrderSupplier::instance()->rows([
            ['bid','=',$binfo['bid']],
            ['order_sn','=',$order_sn],
            ['order_status','=',0],
        ]);

        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"当前订单信息不存在");
        }

        $real_total_moneys = array_sum(array_column($orderInfo, 'real_total_money'));
        $currentOrder = current($orderInfo);
        $receive_address_info = \implode("",[
            $currentOrder['province'],
            $currentOrder['city'],
            $currentOrder['district'],
            $currentOrder['receive_address'],
        ]);
        $payInfo = [
            'cd'                    => $currentOrder['cd'],
            'order_sn'              => $order_sn,
            'pay_money'             => number_format($real_total_moneys,2),
            'receiver_name'         => $currentOrder['receive_name'],
            'receiver_phone'        => $currentOrder['recveive_phone'],
            'order_remark'          => $currentOrder['order_remark'],
            'receive_address_info'  => $receive_address_info,
        ];
        return Normal::returnCode(Normal::SUC,"支付订单信息获取成功",$payInfo);
    }

    /**
     * 获取支付结果
     */
    public function getOrderPayResult( $param = [] )
    {
        $body = $param['body'];
        if( empty($body['order_id']) ) {
            return Normal::returnCode(Normal::FAIL,"except param order_id");
        }

        $order_id = $body['order_id'];
        $where = [];
        if( QueryGoodsMicService::instance()->checkIsAllowedCustomsDeclarationSplit($body['pay_way']) ) {
            $where = ['order_sn' => $order_id];
        } else {
            $where = ['id' => $order_id];
        }

        $orderInfo = $this->info($where,['order_sn',Db::raw("sum(real_total_money) as money")]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单数据不能为空");
        }

        $orderInfo['pay_status']    = 1;
        $orderInfo['order_status']  = 1;
        $orderInfo['pay_remark']    = "支付成功";
        return Normal::returnCode(Normal::SUC,"获取成功数据成功",[
            'orderInfo' => [
                'order_sn'          => $orderInfo['order_sn'],
                'real_total_money'  => number_format((float)$orderInfo['money'],2),
                'order_status'      => 1,
                'pay_status'        => 1,
                'pay_remark'        => "支付成功",
                'pay_way'           => $body['pay_way']??0,
            ]
        ]);
    }

    /**
     * 通联查询支付接口
     * @param array $param
     * @return array
     */
    public function alinOrderPayResult( $param = [] )
    {
        $body = $param['body'];
        if( empty($body['order_sn']) ) {
            return Normal::returnCode(Normal::FAIL,"except param order_sn");
        }

        $order_sn = $body['order_sn'];
        $orderInfo = $this->info(['order_sn' => $order_sn],[
            'id as order_id',
            'order_sn',
            'order_status',
            'pay_status',
            'pay_remark',
            'pay_way'
        ]);

        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单数据不能为空");
        }


        if ($orderInfo['order_status']==1 || $orderInfo['order_status']==200){
            return Normal::returnCode(Normal::SUC,"获取数据成功",[
                'orderInfo' => $orderInfo
            ]);
        }

        return Normal::returnCode(Normal::FAIL,"尚未支付");
    }

    /**
     * 订单支付金额
     * @param array $param
     */
    public function orderPay( $param = [] )
    {
        $binfo = $param['binfo'];
        $body  = $param['body'];
        if( empty($body['order_sn']) ) {
            return Normal::returnCode(Normal::FAIL,"except param order_sn");
        }

        if( !isset($body['pay_way']) ) {
            return Normal::returnCode(Normal::FAIL,"except param pay_way");
        }

        if( !isset($body['pay_type']) ) {
            return Normal::returnCode(Normal::FAIL,"except param pay_type");
        }

        $pay_way = $body['pay_way'];
        if ( !isset($this->pay_way[$pay_way]) ) {
            return Normal::returnCode(Normal::FAIL,"当前接入方式不存在");
        }

        if ( empty($this->pay_way[$pay_way]['client']) ) {
            return Normal::returnCode(Normal::FAIL,"当前接入方式支付类不存在");
        }

        if( $body['pay_type'] == PAY_TYPE_ORDER ) {
            return $this->OnlineOrderPay($param);//在线下单支付
        } else if( $body['pay_type'] == PAY_TYPE_RECHARGE ) {
            return $this->OnlineRechargeOrderPay($param);//在线充值支付
        } else {
            return Normal::returnCode(Normal::FAIL,"支付模式不正确");
        }
    }

    /**
     * 在线下单支付
     * @param array $param
     */
    public function OnlineOrderPay( $param = [] )
    {
        $binfo      = $param['binfo'];
        $body       = $param['body'];
        $bid        = $binfo['bid'];
        $order_sn   = $body['order_sn'];
        $pay_type   = $body['pay_type'];
        $pay_way    = $body['pay_way'];

        //查询订单是否支付
        $orderInfo = OrderSupplier::instance()->rows([
            ['bid','=',$bid],
            ['order_sn','=',$order_sn],
            ['order_status','=',0],
        ]);

        if( empty($orderInfo)) {
            return Normal::returnCode(Normal::FAIL,"订单信息不存在");
        }

        $real_total_moneys = array_sum(array_column($orderInfo, 'real_total_money'));
        $currentOrder = current($orderInfo);
        $id = QueryGoodsMicService::instance()->checkIsAllowedCustomsDeclarationSplit($pay_way) ? $order_sn : $currentOrder['id'];
        $payInfo = [
            'id'                => $id,
            'bid'               => $bid,
            'order_sn'          => $order_sn,
            'pay_money'         => $real_total_moneys,
            'buyer_idcard'      => $currentOrder['buyer_idcard'],
            'buyer_realname'    => $currentOrder['buyer_realname'],
            'buyer_phone'       => $currentOrder['buyer_phone'],
        ];
        $orderGoods = OrderSupplierGoods::instance()->rows(['order_id'=>$currentOrder['id'],'bid'=>$currentOrder['bid']],['goods_name','quantity','spec_num']);
        $client     = $this->pay_way[$pay_way]['client'];
        $res = $client::instance()->OrderPay([
            'payInfo'       => $payInfo,
            'orderGoods'    => $orderGoods,
            'pay_type'      => $pay_type
        ]);

        if( $res['code'] != Normal::SUC ) {
            return $res;
        }

        //加入订单信息
        $res['data']['receive_address_info'] = \implode("",[
            $currentOrder['province'],
            $currentOrder['city'],
            $currentOrder['district'],
            $currentOrder['receive_address'],
        ]);
        $res['data']['pay_money']           = number_format((float)$real_total_moneys,2);
        $res['data']['receive_name']        = $currentOrder['receive_name'];
        $res['data']['recveive_phone']      = $currentOrder['recveive_phone'];
        $res['data']['order_remark']        = $currentOrder['order_remark'];
        $res['data']['order_sn']            = $currentOrder['order_sn'];
        $res['data']['cd']                  = $currentOrder['cd'];

        //写入请求结果
        $where = [
            'bid'       => $bid,
            'order_sn'  => $order_sn,
        ];
        $data = [
            'pay_way'              => $pay_way,
            'apply_request'        => json_encode($res['data'],JSON_UNESCAPED_UNICODE),
            'apply_request_time'   => time(),
        ];
        OrderSupplier::instance()->edit($where,$data);
        return $res;
    }

    /**
     * 在线充值支付
     * @param array $param
     */
    public function OnlineRechargeOrderPay( $param = [] )
    {
        $binfo      = $param['binfo'];
        $body       = $param['body'];
        $bid        = $binfo['bid'];
        $order_sn   = $body['order_sn'];
        $pay_type   = $body['pay_type'];
        $pay_way    = $body['pay_way'];
        if( $binfo['user_source'] != 2 ) {
            return Normal::returnCode(Normal::FAIL,"非渠道商用户不能进行在线充值操作");
        }

        if( empty($body['pay_money']) ) {
            return Normal::returnCode(Normal::FAIL,"充值金额不能为空");
        }

        $pay_money = $body['pay_money'];
        //获取实名认证信息
        $userAddrInfo = MerchantAdress::instance()->info(['bid'=>$bid]);
        if( empty($userAddrInfo) ) {
            return Normal::returnCode(Normal::FAIL,"请先进行实名认证收货地址绑定");
        }
        //添加充值记录
        try {
            self::startTrans();
            $order_id = IdService::instance()->getOtherID();
            $insertRecharge = [
                "id"                => $order_id,
                "bid"               => $bid,
                "pay_way"           => $pay_way,
                "order_sn"          => $order_sn,
                "money"             => $pay_money,
                "recharge_status"   => 0,
                "remark"            => "在线充值",
                "cd"                => time()
            ];
            $res = OrderRecharge::instance()->insert($insertRecharge);
            if( !$res ) {
                self::rollback();
                return Normal::returnCode(Normal::FAIL,"系统繁忙，请稍后再试");
            }

            $payInfo = [
                'id'                => $order_sn,
                'bid'               => $bid,
                'order_sn'          => $order_sn,
                'pay_money'         => $pay_money,
                'buyer_idcard'      => $userAddrInfo['receive_id_card'],
                'buyer_realname'    => $userAddrInfo['buyer_realname'],
                'buyer_phone'       => $userAddrInfo['buyer_phone'],
            ];
            $client = $this->pay_way[$pay_way]['client'];
            $res = $client::instance()->OrderPay([
                'payInfo'       => $payInfo,
                'orderGoods'    => [],
                'pay_type'      => $pay_type
            ]);

            if( $res['code'] == Normal::SUC ) {
                self::commit();
            } else {
                self::rollback();
            }

            return $res;
        } catch ( \Throwable $e ) {
            self::rollback();
            return Normal::returnCode(Normal::FAIL,$e->getMessage());
        }
    }

    /**
     * 在线充值订单记录列表
     */
    public function orderRechargePageList( $param = [] )
    {
        $binfo  = $param['binfo'];
        $body   = $param['body'];
        $page   = $body['page'] ?? 0;
        $limit  = $body['limit'] ?? 10;
        $columns = [
            "order_sn",
            "pay_sn",
            "pay_way",
            "money",
            "recharge_status",
            "recharge_result",
            "cd",
            "md"
        ];

        $page_data = OrderRecharge::instance()
            ->where("bid",$binfo['bid'])
            ->orderBy("cd","desc")
            ->paginate($limit, $columns, 'page', $page)
            ->toArray();

        $page_data['data'] = array_map(function( & $value){
            $value['cd'] = date("Y-m-d",$value['cd']);
            $value['md'] = $value['md'] ? date("Y-m-d",$value['md']) : '';
            $value['recharge_status_name'] = OrderRecharge::instance()->recharge_status[$value['recharge_status']]??'';
            $value['pay_way_name'] = $this->pay_way[$value['pay_way']]['client_name']??'';
            return $value;
        },$page_data['data']);
        return Normal::returnCode(Normal::SUC,"获取成功",$page_data);
    }

    /**
     * $param['orderType'] 1-立即下单，2-购物车结算
     * 商城前台下单详情页面接口
     * @param array $param
     */
    public function placeOrderDetai( $param = [] )
    {
        $binfo = $param['binfo'];
        $body  = $param['body'];
        if( empty($body['orderKey']) ) {
            return Normal::returnCode(Normal::FAIL,"except param orderKey");
        }

        if( empty($body['orderType']) || !in_array($body['orderType'], [1,2]) ) {
            return Normal::returnCode(Normal::FAIL,"except param orderType");
        }

        $orderType  = $body['orderType'];
        $orderKey   = $body['orderKey'];
        $redis = BaseService::instance()->getRedisObj();
        $redis->select(QueryGoodsMicService::RDB_ORDER_GOODS_NUM);
        $cache = $redis->get(QueryGoodsMicService::REDIS_KEY_GOODS.$orderKey);
        if( empty($cache) ) {
            return Normal::returnCode(Normal::FAIL,"当前商品下单信息已失效，请回到商品详情页面重新下单购买");
        }

        $placeOrderInfo = @json_decode($cache,true);
        if( empty($placeOrderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"商品下单异常");
        }

        $orderGoods = $placeOrderInfo['orderGoods'];
        $goodsInfo  = $placeOrderInfo['goodsInfo'];
        $parameters = [
            'binfo' => $binfo,
            'body'  => [
                'goods_list' => $orderGoods,
            ]
        ];
        $res = QueryGoodsMicService::instance()->checkGoodsOrderBatch($parameters);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        //获取微服务商品数据结构
        $goodsInfo      = $res['data']['goodsInfo'];
        $goodsInfoMap   = array_column($goodsInfo,null,'goods_id');
        $orderGoods     = $res['data']['orderGoods'];

        //收货地址获取对应运费配置
        $address_id = $body['address_id'] ?? 0 ;
        if( $address_id > 0 ) {
            $res = $this->getDeliveryTemplateByAddressId($address_id);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }
            $regions = $res['data'];

            //获取所有运费模板的最佳模板（区 -> 市 -> 省 -> 全国）反找
            $template_ids = array_column($goodsInfo, 'freight_template_id');
            $template_ids = array_filter(array_unique($template_ids));
            $templateList = TemplateDeliveryArea::instance()->getGoodsTemplateByIds($template_ids);

            //计算获取每个模板对应区域运费
            $res = TemplateArea::instance()->getUserRegionIdsByAddress($templateList,$regions);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }
            $template_list = $res['data']['template_list'];

            //获取总运费
            $res = $this->getFreightTemplateBySupplierGroupGoods($orderGoods,$goodsInfo,$template_list);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }

            //订单预估总税费
            $delivery_weight_total  = $res['data']['total_freight'];
        } else {
            $delivery_weight_total  = '0.00';
        }
        $orderGoodsItem         = [];
        $goodsTotalMoney        = 0;
        $tax_total = 0;

        //是否是需要填充身份证号
        $isNeedIdCards = [];
        foreach ($orderGoods as $item )
        {
            if( !isset($goodsInfoMap[$item['goods_id']]) )
            {
                continue;
            }

            $currentGoods    = $goodsInfoMap[$item['goods_id']];

            //判断不需要检查
            if( $currentGoods['is_check_idcard'] == 1 ) {
                $isNeedIdCards[] = 1;
            }

            $storeInfo      = current($currentGoods['storeList']);
            $goodsBatchInfo = current($storeInfo['goods_batch_list']);
            $spec_list      = array_column($goodsBatchInfo['spec_list'],null,'spec_num');
            if( !isset($spec_list[$item['spec_num']]) ) {
                return Normal::returnCode(Normal::FAIL,"商品【{$currentGoods['goods_name']}】批次【{$goodsBatchInfo['batch_no']}】下规格【{$item['spec_num']}】已下架，请先从购物车中移除之后再进行结算!");
            }

            $price          = $spec_list[$item['spec_num']]['price'];
            $total_money    = bcmul((string)$item['goods_num'], (string)$price,2);
            $tax_rate       = bcadd('1', (string)$currentGoods['tax'],4);
            $singleTax              = bcdiv((string)$price,$tax_rate,2);
            $singleTax              = bcsub((string)$price,$singleTax,2);
            $singleTaxAll           = bcmul((string)$item['goods_num'],$singleTax,2);
            $orderGoodsItem[] = [
                "cart_id"           => $item['cart_id']??'',
                "goods_type"        => $currentGoods['goods_type'],
                "goods_type_name"   => $currentGoods['goods_type_name'],
                "goods_id"          => $currentGoods['goods_id'],
                "skucode"           => $currentGoods['skucode'],
                "barcode"           => $currentGoods['barcode'],
                "goods_name"        => $currentGoods['goods_name'],
                "image"             => $currentGoods['image'],
                "price"             => $price,
                'tax'               => $currentGoods['tax'],
                "batch_no"          => $goodsBatchInfo['batch_no'],
                "spec_num"          => $item['spec_num'],
                "goods_num"         => $item['goods_num'],
                "total_money"       => $total_money,
            ];
            $tax_total=bcadd($singleTaxAll,(string)$tax_total,2);
            $goodsTotalMoney = bcadd((string)$goodsTotalMoney, (string)$total_money,2);
        }

        $realPayMoney = bcadd((string)$delivery_weight_total,(string)$goodsTotalMoney,2);

        $buyerIdCardItem = [];
        $isHaveBuyerIdInfo = 0;
        if( $address_id > 0 ) {
            $address_info = MerchantAdress::instance()->info(['id'=>$address_id]);
            if( !empty($address_info)  && !empty($address_info['receive_realname']) && !empty($address_info['receive_phone']) && !empty($address_info['receive_id_card']) ) {
                $buyerIdCardItem = [
                    'buyer_realname'    => $address_info['receive_realname'],
                    'buyer_phone'       => $address_info['receive_phone'],
                    'buyer_id_card'     => $address_info['receive_id_card'],
                ];
                $isHaveBuyerIdInfo = 1;
            }
        }

        $placeOrderDetail = [
            'goodsTotalMoney'   => $goodsTotalMoney,
            'feight'            => $delivery_weight_total,
            'realPayMoney'      => $realPayMoney,
            'orderGoodsItem'    => $orderGoodsItem,
            'isNeedIdCard'      => $isNeedIdCards ? 1 : 0 ,
            'buyerIdCardItem'   => $buyerIdCardItem,
            'isHaveBuyerIdInfo' => $isHaveBuyerIdInfo,
            'taxAll'            => $tax_total
        ];
        return Normal::returnCode(Normal::SUC,"获取成功",$placeOrderDetail);
    }

    /**
     * 更具供应商商品分组计算运费
     * 如果是合并支付下单的仓库，只收取一个首重费用，如果是不支持合并支付的供应商仓库，按照仓库分组进行收取订单首重费用
     * @param $address_id
     */
    public function getFreightTemplateBySupplierGroupGoods($orderGoods,$goodsInfo,$template_list)
    {
        $group_goods   = [];
        foreach ($goodsInfo as $item)
        {
            $supplier_id = $item['supplier_id'];
            $group_goods[$supplier_id]['supplier_id']           = $supplier_id;
            $group_goods[$supplier_id]['is_combine']            = $item['is_combine'];
            $group_goods[$supplier_id]['goods_list'][]          = $item;
            unset($item);
        }

        rsort($group_goods);
        $orderGoodsMap = [];
        foreach ($orderGoods as $item ){
            $orderGoodsMap[$item['goods_id']][] = $item;
            unset($item);
        }

        $total_freight = '0.00';
        //对分组出来的商品进行运费拆解
        foreach ($group_goods as $item )
        {
            $goods_list             = $item['goods_list'];
            $is_combine             = $item['is_combine'];
            $freight_template_ids  = array_column($goods_list,'freight_template_id');
            $freight_template_ids  = array_unique($freight_template_ids);

            //实际获取到运费模板
            $res = TemplateDeliveryArea::instance()->getMostHighFreightMoney($template_list,$freight_template_ids);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }
            $price_template = $res['data'];

            //处理商品运费
            $total_weight_g_all  = 0;
            $money               = 0;
            $total_cost_post_fee = 0;
            foreach ($goods_list as $goods )
            {
                if( !isset($orderGoodsMap[$goods['goods_id']]) ) {
                    return Normal::returnCode(Normal::FAIL,"商品【{$goods['goods_id']}】已下架，请先从购物车中移除之后再进行结算!");
                }

                //获取下单商品
                $currentGoods       = $orderGoodsMap[$goods['goods_id']];
                $goods_batch_list   = current($goods['storeList'])['goods_batch_list'];
                $goods_batch_list   = array_column($goods_batch_list,null,'batch_no');
                $cost_post_fee      = 0;
                foreach ($currentGoods as $currentOrderGoods )
                {
                    $batch_no   = $currentOrderGoods['batch_no'];
                    $spec_num   = $currentOrderGoods['spec_num'];
                    $goods_num  = $currentOrderGoods['goods_num'];
                    if( !isset($goods_batch_list[$batch_no]) ) {
                        return Normal::returnCode(Normal::FAIL,"商品【{$goods['goods_id']}】批次【{$batch_no}】已下架，请先从购物车中移除之后再进行结算!");
                    }
                    $spec_list = array_column($goods_batch_list[$batch_no]['spec_list'],null,'spec_num');
                    if( !isset($spec_list[$spec_num]) ) {
                        return Normal::returnCode(Normal::FAIL,"商品【{$goods['goods_name']}】批次【{$batch_no}】下规格【{$spec_num}】已下架，请先从购物车中移除之后再进行结算!");
                    }
                    //成本邮费
                    $cost_post_fee=$spec_list[$spec_num]['priceCostPost']??0;
                    $cost_post_fee=bcmul((string)$goods_num,(string)$cost_post_fee,2);
                }
                
                //是否包邮
//                $is_free_postfee = $goods['is_free_postfee'];
//                if( ! $is_free_postfee ) {
                //单件装商品重量
                $weight             = $goods['weight'];
                //单商品总重量
                $total_weight_g     = $spec_num * $goods_num * $weight ;
                $total_weight_g_all = $total_weight_g_all + $total_weight_g;
                $total_cost_post_fee = $total_cost_post_fee + $cost_post_fee;
                if( !$is_combine ) {//非合并支付，按照单个订单计算金额
                    $money = TemplateDeliveryArea::instance()->getFreightMoneyByTemplateAndWeight($price_template,$total_weight_g);
                    if ($money>$cost_post_fee){
                        $money=bcsub((string)$money,$cost_post_fee,2);
                        $total_freight = bcadd($money,(string)$total_freight,2);
                    }
                }
//                }
            }
            if( $is_combine) {//合并支付，算子单总运费
                $money = TemplateDeliveryArea::instance()->getFreightMoneyByTemplateAndWeight($price_template,$total_weight_g_all);
                if ($money>$total_cost_post_fee){
                    $money=bcsub((string)$money,(string)$total_cost_post_fee,2);
                    $total_freight=bcsub($money,(string)$total_freight,2);
                }
            }
        }

        return Normal::returnCode(Normal::SUC,"获取运费成功",[
            'total_freight' => $total_freight
        ]);
    }

    /**
     * 收货地址ID计算运费
     * @param $address_id
     */
    public function getDeliveryTemplateByAddressId($address_id )
    {
        $address_info = MerchantAdress::instance()->info(['id'=>$address_id]);
        if( empty($address_info) ) {
            return Normal::returnCode(Normal::FAIL,"当前收货地址未找到，请刷新页面重试");
        }
        $province = $address_info['province'];
        $city     = $address_info['city'];
        $district = $address_info['district'];
        $areaids  = [$province,$city,$district];
        $areainfo = Area::instance()->whereIn('area_id',$areaids)->get()->toArray();
        if( empty($areainfo) || count($areaids) != 3) {
            return Normal::returnCode(Normal::FAIL,"当前收货地址省市区信息未找到，请刷新页面重试");
        }

        $areainfo = array_column($areainfo,'area_name','area_id');
        //获取高德省市区信息
        return TemplateDeliveryArea::instance()->getDeliveryAddressInfoByAddress([
            'province'          => $areainfo[$province],
            'city'              => $areainfo[$city],
            'district'          => $areainfo[$district],
            'receiveAddress'    => $address_info['receive_address'],
        ]);
    }

    /**
     * 立即下单接口
     * @param array $param
     */
    public function placeOrder( $param = [] )
    {
        $binfo = $param['binfo'];
        $body  = $param['body'];
        if( empty($body['address_id']) ) {
            return Normal::returnCode(Normal::FAIL,"请先添加收货地址！");
        }

        if( empty($body['orderType']) ) {
            return Normal::returnCode(Normal::FAIL,"except param orderType");
        }

        //检查收货地址是否正确
        $address_id = $body['address_id'];
        $orderType = $body['orderType'];
        $res = MerchantAdress::instance()->checkAddress([
            'bid'   => $binfo['bid'],
            'id'    => $address_id
        ]);

        if( $res['code'] != Normal::SUC ) {
            return $res;
        }

        //收货地址
        $addressInfo = $res['data'];

        if( empty($body['goods_list']) ) {
            return Normal::returnCode(Normal::FAIL,"except param goods_list");
        }

        $goods_list = $body['goods_list'];
        $isSplitOrder = QueryGoodsMicService::instance()->checkIsAllowedCustomsDeclarationSplit($body['pay_way']);
        if( count($goods_list) > 1 && !$isSplitOrder  ) {
            return Normal::returnCode(Normal::FAIL,"仅支持单商品下单");
        }

        //获取商品下单价格和下单信息
        $res = QueryGoodsMicService::instance()->checkGoodsOrderBatch($param);
        if($res['code'] != Normal::SUC ) {
            return $res;
        }

        $goodsInfo      = array_column($res['data']['goodsInfo'],null,'goods_id');
        $orderGoodsList = [];
        $goodsMoney     = 0;
        $authGoodsList  = [];

        //收货地址获取对应运费配置
        $address_id = $body['address_id'] ?? 0 ;
        $res = $this->getDeliveryTemplateByAddressId($address_id);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $regions = $res['data'];
        //获取所有运费模板的最佳模板（区 -> 市 -> 省 -> 全国）反找
        $template_ids = array_column($goodsInfo, 'freight_template_id');
        $template_ids = array_filter(array_unique($template_ids));
        $templateList = TemplateDeliveryArea::instance()->getGoodsTemplateByIds($template_ids);

        //计算获取每个模板对应区域运费
        $res = TemplateArea::instance()->getUserRegionIdsByAddress($templateList,$regions);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $template_list = $res['data']['template_list'];

        //订单预估总税费
        $res = $this->getFreightTemplateBySupplierGroupGoods($goods_list,$goodsInfo,$template_list);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $delivery_weight_total  = $res['data']['total_freight'];

        //是否是需要填充身份证号
        $isNeedIdCards = [];
        foreach ($goods_list as $key => $item )
        {
            $goods_id = $item['goods_id'];
            if( !isset($goodsInfo[$goods_id]) ) {
                return Normal::returnCode(Normal::FAIL,"当前商品已下架-1");
            }

            //当前批次号
            $batch_no           = $item['batch_no'];
            $currentGoods       = $goodsInfo[$goods_id];
            //判断不需要检查
            if( $currentGoods['is_check_idcard'] == 1 ) {
                $isNeedIdCards[] = 1;
            }

            $storeList          = current($currentGoods['storeList']);
            $goods_batch_list   = array_column($storeList['goods_batch_list'],null,'batch_no');
            if( !isset($goods_batch_list[$batch_no]) ) {
                return Normal::returnCode(Normal::FAIL,"当前商品已下架-2");
            }

            $currentSpecList    = $goods_batch_list[$batch_no]['spec_list'];
            $spec_list          = array_column($currentSpecList,null,'spec_num');
            $spec_num           = $item['spec_num'];
            $goods_num          = $item['goods_num'];
            if( !isset($spec_list[$spec_num]) ) {
                return Normal::returnCode(Normal::FAIL,"当前商品已下架-3");
            }

            //下单价格
            $price = $spec_list[$spec_num]['price'];

            //下单商品组
            $orderGoodsList[] = [
                "gIndex"        =>  $key + 1,
                "commodityName" =>  $currentGoods['goods_name'],
                "goodsSku"      =>  $currentGoods['skucode'],
                "goodsNum"      =>  $item['goods_num'],
                "goodsBatchNo"  =>  $batch_no,
                "goodsTax"      =>  0.00,//税费默认不拆分
                "goodsPrice"    =>  $price,
                "goodsSpecNum"  =>  $spec_num,
                "startExpDate"  =>  $batch_no,
                "endExpDate"    =>  $batch_no,
                "seckill_info"  =>  $spec_list[$spec_num]['seckill_info']??'',
            ];

            //商品金额
            $goodsMoney = bcadd((string)$goodsMoney, bcmul((string)$price, (string)$goods_num,2),2);

            //组装模拟授权价格数据,供下单使用
            $authGoodsList[$currentGoods['skucode']] = [
                'goods_id'      => $goods_id,
                'skucode'       => $currentGoods['skucode'],
                'barcode'       => $currentGoods['barcode'],
                'spec_list'     => json_encode($currentSpecList,JSON_UNESCAPED_UNICODE)
            ];
        }

        //获取真实商品价格数据
        $args = [
            'bid'           => 0,
            'goods_list'    => $goods_list
        ];
        
        $res = callRpcCommodityServer('getRealGoodsList',$args);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }

        $realGoodsList  = $res['data'];
        $realPayMoney   = bcadd((string)$delivery_weight_total, (string)$goodsMoney,2);
        $order_remark   = $body['order_remark'] ??'';
        $order_sn       = date('YmdHis').substr(microtime(), 2,6);

        if( !empty($isNeedIdCards) && (empty($body['buyer_realname']) || empty($body['buyer_phone']) || empty($body['buyer_id_card'])) )
        {
            return Normal::returnCode(Normal::FAIL,"请先完善订购人身份信息！");
        }

        //处理添加订购人信息
        if( !empty($isNeedIdCards) ) {

            $resAuthCheck = MerchantAdress::instance()->idcardauth([
                'name'      => $body['buyer_realname'],
                'idNum'     => $body['buyer_id_card'],
            ]);

            if( $resAuthCheck['code'] != Normal::SUC ) {
                return $resAuthCheck;
            }

            MerchantBuyer::instance()->checkAddUserBuyerInfo($binfo,$body);
        }

        //组装订单数据
        $orderData = [
            'bid'               => $binfo['bid'],
            'binfo'             => $binfo,
            'appid'             => $binfo['appid'],
            'requestMethod'     => 'createOrder',
            'requestData'       => [
                'orderSn'           => $order_sn,
                'buyerRealName'     => !empty($body['buyer_realname']) ? $body['buyer_realname'] : $addressInfo['receive_realname'],
                'buyerPhone'        => !empty($body['buyer_phone']) ? $body['buyer_phone'] : $addressInfo['receive_phone'],
                'buyerIdCard'       => $body['buyer_id_card'] ?? '',
                'receiveAddress'    => $addressInfo['receive_address'],
                'receiveName'       => $addressInfo['receive_realname'],
                'recveivePhone'     => $addressInfo['receive_phone'],
                'province'          => $addressInfo['provice_name'],
                'city'              => $addressInfo['city_name'],
                'district'          => $addressInfo['district_name'],
                'orderRemarks'      => $order_remark,
                'freight'           => $delivery_weight_total,
                'freightTax'        => 0.00,
                'discountMoney'     => 0.00,
                'orderMoney'        => $realPayMoney,
                'orderMode'         => 1,
                'isOpen'            => 1,
                'orderSource'       => '云仓商城',
                'order_type'        => 1,
                'isPayDeclare'      => 1,//已申报支付单
                'isSplitOrder'		=> $isSplitOrder,//是否拆单
                'goods'             => $orderGoodsList,//下单商品
                'realGoodsList'     => $realGoodsList,//组装原始商品
                'authGoodsList'     => $authGoodsList,//组装授权商品
                'templateList'      => $template_list,//模板列表
            ]
        ];
        $res = CreateOrder::instance()->index($orderData);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }

        //购物车下单成功，删除购物车数据
        if( $orderType == 2 ) {
            $currentCartGoods = current($goods_list);
            if( !isset($currentCartGoods['cart_id']) ) {
                return Normal::returnCode(Normal::FAIL,"except goods_list.cart_id");
            }

            //下单成功删除购物车数据
            $cartIds = array_column($goods_list, 'cart_id');
            GoodsCart::instance()->whereIn('id',$cartIds)->where('bid',$binfo['bid'])->delete();
        }

        //下单成功，删除临时缓存key
        if( isset($body['orderKey']) && isset($body['orderType']) ) {
            $redis = BaseService::instance()->getRedisObj();
            $redis->select(QueryGoodsMicService::RDB_ORDER_GOODS_NUM);
            $key   = QueryGoodsMicService::REDIS_KEY_GOODS.$body['orderType'];
            $redis->del($key);
        }

        $arr = [
            'order_sn'          => $order_sn,
            'realPayMoney'      => number_format((float)$realPayMoney,2),
            'discountMoney'     => number_format((float)0.00,2),
            'createOrderTime'   => time(),
            'receiveUserInfo'   => implode("", [
                $addressInfo['receive_realname']." ",
                $addressInfo['provice_name'],
                $addressInfo['city_name'],
                $addressInfo['district_name'],
                $addressInfo['receive_address']
            ]),
        ];
        return Normal::returnCode(Normal::SUC,"下单成功",$arr);
    }

    /**
     * 取下订单接口
     * @param array $param
     */
    public function orderCancel( $param = [] )
    {
        $body = $param['body'];
        $binfo = $param['binfo'];
        if( empty($body['order_sn']) ) {
            return Normal::returnCode(Normal::FAIL,"except param order_sn");
        }

        if( empty($body['exceptReason']) ) {
            return Normal::returnCode(Normal::FAIL,"取消订单原因必须填写");
        }

        return OrderCancel::instance()->index([
            'bid'   => $binfo['bid'],
            'binfo' => $binfo,
            'requestData' => [
                'orderSn'       => $body['order_sn'],
                'exceptReason'  => $body['exceptReason']
            ]
        ]);
    }

    /**
     * 订单售后接口
     * @param array $param
     */
    public function orderAfterSale( $param = [] )
    {
        $body = $param['body'];
        $binfo = $param['binfo'];
        if( empty($body['order_id']) ) {
            return Normal::returnCode(Normal::FAIL,"except param order_id");
        }

        if( empty($body['exceptReason']) ) {
            return Normal::returnCode(Normal::FAIL,"售后原因必须填写");
        }

        if( !isset($body['after_sale_status'])) {
            return Normal::returnCode(Normal::FAIL,"except param after_sale_status");
        }

        //获取单个订单信息
        $where = ['id' => $body['order_id'],'bid' => $binfo['bid']];
        $select = [
            'id',
            'order_sn',
            'after_sale_status',
            'supplier_csn'
        ];
        $supplierOrder = OrderSupplier::instance()->info($where,$select);
        if( empty($supplierOrder) ) {
            return Normal::returnCode(Normal::FAIL,"当前订单信息不存在");
        }

        if( $supplierOrder['after_sale_status'] == 1 ) {
            return Normal::returnCode(Normal::FAIL,"当前订单已申请售后，无需再申请");
        }

        return OrderAfterSale::instance()->index([
            'bid'   => $binfo['bid'],
            'binfo' => $binfo,
            'requestData' => [
                'order_sn'          => $supplierOrder['order_sn'],
                'after_sale_status' => $body['after_sale_status'] ,
                'exceptReason'      => $body['exceptReason'],
                'isSingleOrder'     => 1,
                'orderNo'           => $supplierOrder['supplier_csn']
            ]
        ]);
    }

    /**
     * 处理订单号
     * @param string $supplier
     */
    public function getCreateOrderSn( $supplier = null) {
        return implode("",[
            $supplier,
            IdService::instance()->getOtherID()
        ]);
    }

    /**
     * 组装供应商子订单数据
     * @param array $param
     */
    public function getSupplierCreateOrderData( $param = [] )
    {
        $res = $this->getOrderGoodsData($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }

        $orderGoodsList             = $res['data'];
        $supplierGoodsInfo          = $param['supplierGoodsInfo'];
        //是否合并下单字段，这里订单订单已经分组好了，没有意义了，此字段只是在商城计算运费显示的时候有作用，但实际运费已子订单拆单为准
        $isCombineOrders            = $supplierGoodsInfo['isCombineOrders'];
        //当前子订单商品总重量
        $totalWeight                = $orderGoodsList['totalWeight'];
        //获取当前子订单商品运费最高的模板（最高规则：首重价格 + 续重价格/kg）
        $template_ids               = $orderGoodsList['currentOrderTemplateList'];
        //是否计算运费
        $isNoFreeShipping           = $orderGoodsList['isNoFreeShipping'];
        //如果存在运费模板明细、否则就是京东、拼多多渠道下单
        if( isset($param['order']['templateList']) && !empty($param['order']['templateList']) && !empty($isNoFreeShipping) ) {
            //所有下单商品涉及的运费模板
            $templateList = $param['order']['templateList'];
            //获取实际计算的运费模板
            $res = FreightTemplateArea::instance()->getMostHighFreightMoney($templateList,$template_ids);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }
            $template_info = $res['data'];
            $total_template_delivery = FreightTemplateArea::instance()->getFreightMoneyByTemplateAndWeight($template_info,$totalWeight);//根据重量和运费模板计算运费
            $orderGoodsList['total_template_delivery'] = $total_template_delivery;
            $orderGoodsList['template_info'] = $template_info;
        } else {//不参与结算
            $orderGoodsList['total_template_delivery'] = $total_template_delivery = 0.00;
            $orderGoodsList['template_info'] = [];
        }

        $supplierOrder           = $this->getSupplierOrderData($param,$orderGoodsList);
        $order_goods             = $orderGoodsList['order_goods'];
        //拆单之后每个订单子信息
        $orderItems = [
            "orderSn"               => (string)$supplierOrder['order_sn'],
            "orderNo"               => (string)$supplierOrder['supplier_csn'],
            "orderStatus"           => 0,
            "isPay"                 => true,
            "goodsMoney"            => $supplierOrder['goods_money'],
            "deliverMoney"          => $supplierOrder['deliver_money'],
            "totalTemplateDelivery" => $total_template_delivery,
            "discountMoney"         => $orderGoodsList['total_discountMoney'],
            "totalMoney"            => $supplierOrder['total_money'],
            "invoiceMoney"          => 0.00,
            "realTotalMoney"        => $supplierOrder['real_total_money'],
            "goods_items"           => $orderGoodsList['orderItemsList']
        ];

        $orderSupplierId = $supplierOrder['id'];
        $order_goods = array_map(function( $value) use( $orderSupplierId ){
            $value['order_id'] = $orderSupplierId;
            return $value;
        },$order_goods);
        
        
        $placeOrderInfo = $param['order'];
        
        //订单其它消费金额扩展表
        $supplierAmountExtra = [
            'order_id'                      => $orderSupplierId,
            'discount_money'                => $orderGoodsList['total_discountMoney'],
            'discount_points_money'         => $orderGoodsList['discount_points_money'],
            'discount_red_envelope_money'   => $orderGoodsList['discount_red_envelope_money'],
            'discount_activity_money'       => $orderGoodsList['discount_activity_money'],
            'discount_activity_name'        => $placeOrderInfo['discountActivityName'] ?? '',
            'discount_coupon_money'         => $orderGoodsList['discount_coupon_money'],
            'discount_coupon_names'         => $placeOrderInfo['discountCouponNames'] ?? '',
            'discount_payway_money'         => $orderGoodsList['discount_payway_money'],
            'discount_red_envelope_name'    => $placeOrderInfo['discountRedEnvelopeName'] ?? '',
            'order_pre_sale_stage'          => $placeOrderInfo['orderPreSaleStage'] ?? '0',
            'order_precard_balance_money'   => $placeOrderInfo['orderPrecardBalanceMoney'] ?? '0.00',
            'order_points'                  => $placeOrderInfo['orderPoints'] ?? '0.00',
            'cd'                            => time(),
        ];
        
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'order'                 => $supplierOrder,
            'goods'                 => $order_goods,
            'orderItems'            => $orderItems,
            'seckill_info'          => $orderGoodsList['seckill_info'],
            'supplierAmountExtra'   => $supplierAmountExtra
        ]);
    }

    /**
     * 获取主订单结构数据信息
     * @param array $param
     */
    public function getUserMainOrderInfo( $param = [] )
    {
        $res = $this->getUserOrderGoodsData($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }

        $orderGoods     = $res['data'];
        $order          = $this->getUserOrderData($param,$orderGoods);
        $order_goods    = $orderGoods['order_goods'];
        $orderId        = $order['id'];
        $order_goods = array_map(function( $value) use( $orderId ){
            $value['order_id'] = $orderId;
            return $value;
        },$order_goods);
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'order' => $order,
            'goods' => $order_goods,
            'stockDeductInfo' => $orderGoods['stockDeductInfo']
        ]);
    }

    /**
     * 组装主订单数据
     * @param array $param
     */
    public function getUserOrderData( $param = [] ,$goodsInfo = [] )
    {
        $binfo = $param['binfo'];
        $placeOrderInfo = $param['order'];

        //处理订单金额
        $settlement_total_money = $goodsInfo['settlement_total_money'];
        $costprice_total_money  = $goodsInfo['costprice_total_money'];
        $price_total_money      = $goodsInfo['price_total_money'];
        $freight_total_money    = $goodsInfo['freight_total_money'];
        $totalMoney             = bcadd((string)$price_total_money, (string)$freight_total_money,2);//订单金额
        //优惠金额
        $discountMoney          = $goodsInfo['total_discountMoney'] ?? 0.00;
        //真实付款金额
        $totalMoney             = bcsub((string)$totalMoney,(string)$discountMoney,2);

        $invoiceMoney           = 0;
        $freightTax             = $placeOrderInfo['freightTax'] ?? 0.00;
        $goodstax               = 0.00;
        $orderTaxFee            = bcadd((string)$goodstax, (string)$freightTax,2);//订单总税费 ： 运费税 + 商品税（商品税目前为0）
        return [
            'id'                    => IdService::instance()->getOmsID(),
            'order_type'            => 2,                                   //订单类型
            'order_from_type'       => isset($binfo['order_type']) ? $binfo['order_type'] : 0,//订单来源类型
            'order_sn'              => $placeOrderInfo['orderSn'],          //商户订单号
            'order_source'          => $placeOrderInfo['orderSource'],      //订单来源
            'bid'                   => $binfo['bid'],                       //商户ID
            'buyer_realname'        => $placeOrderInfo['buyerRealName'],    //下单人
            'buyer_phone'           => $placeOrderInfo['buyerPhone'],       //下单人电话
            'buyer_idcard'          => $placeOrderInfo['buyerIdCard'],      //下单人身份证号
            'receive_name'          => $placeOrderInfo['receiveName'],      //收货人姓名
            'recveive_phone'        => $placeOrderInfo['recveivePhone'],    //收货人电话
            'province'              => $placeOrderInfo['province'],         //省
            'city'                  => $placeOrderInfo['city'],             //市
            'district'              => $placeOrderInfo['district'],         //区
            'receive_address'       => $placeOrderInfo['receiveAddress'],   //收货地址
            'discount_money'        => $discountMoney,                      //优惠金额
            'money'                 => $price_total_money,					//订单商品金额
            'goodstax'              => 0.00,						        //商品税费
            'deliver_money'         => $freight_total_money,                //运费
            'freight'               => $freight_total_money,                //运费
            'freighttax'            => $freightTax,                         //运费税
            'tax'                   => $orderTaxFee,                        //总税费
            'totalmoney'            => $totalMoney,                         //总金额
            'order_costprice'       => $costprice_total_money,              //订单总成本
            'settlementmoney'       => $settlement_total_money,             //结算总价
            'remark'                => $placeOrderInfo['orderRemarks'],     //订单备注
            'cd'                    => time(),                              //创建时间
        ];
    }

    /**
     * 组装主订单商品数据
     * @param array $param
     */
    public function getUserOrderGoodsData( $param = [] )
    {
        $supplierGoodsInfo = $param['supplierGoodsInfo'];
        $binfo             = $param['binfo'];
        $order_type        = $param['order']['order_type'] ?? 0;
        $orderGoods        = [];
        $settlement_total_money = $costprice_total_money = $price_total_money = $freight_total_money = $total_discountMoney = 0 ;
        $stockDeductInfo   = [];
        foreach ($supplierGoodsInfo as $supplierCode => $supplierGoods )
        {
            $orderGoodsList = $supplierGoods['userGoodsList'];
            $userGoodsData  = $supplierGoods['authGoodsList'];
            $orderDockMode  = $supplierGoods['orderDockMode'];
            $canModifyStock  = $supplierGoods['canModifyStock'];
            $fastDeliveryType  = $supplierGoods['FastDeliveryType'];
            $bestGoodsList  = $supplierGoods['goodsList'];
            $bestGoodsList  = array_column($bestGoodsList,null,'skuCode');
            foreach ($orderGoodsList as $skuCode => $skuItem )
            {
                foreach ($skuItem as $item )
                {
                    $skucode        = $item['goodsSku'];
                    $goodsSpecNum   = $item['goodsSpecNum'];
                    $quantity       = $item['goodsNum'];

                    if( !isset($bestGoodsList[$skuCode]) ) {
                        return Normal::returnCode(Normal::FAIL,"{$supplierCode}商品{$skuCode}商品已下架,请重新选择商品进行下单!(100004)");
                    }

                    //当前供应商商品
                    $currentSupplier = $bestGoodsList[$skucode];

                    //当前供应商规格组
                    $specList = array_column($currentSupplier['SpecList'],null,'SpecificationNum');
                    if( !isset($specList[$goodsSpecNum]) ) {
                        return Normal::returnCode(Normal::FAIL,"当前SKU：{$skucode}，规格：{$currentSupplier['batchNo']}，请重新选择商品进行下单!(100005)");
                    }

                    //获取授权商品快照
                    $userGoods              = $userGoodsData[$skucode];
                    $spec_list              = @json_decode($userGoods['spec_list'],true);
                    $spec_list              = array_column($spec_list, null,'spec_num');
                    if( !isset($spec_list[$goodsSpecNum]) ) {
                        return Normal::returnCode(Normal::FAIL,"当前SKU：{$skucode}，规格：{$currentSupplier['batchNo']}，请重新选择商品进行下单!(100006)");
                    }

                    //结算价
                    $settlement_price       = $spec_list[$goodsSpecNum]['priceSettlement'];
                    //成本价
                    $costPrice              = $specList[$goodsSpecNum]['SpecificationPrice'];
                    //销售价
                    $price                  = $item['goodsPrice'];

                    $settlement_total_money = bcadd((string)$settlement_total_money, bcmul((string)$quantity,(string)$settlement_price,2),2);
                    $costprice_total_money  = bcadd((string)$costprice_total_money, bcmul((string)$quantity,(string)$costPrice,2),2);
                    $totalPrice             = bcmul((string)$quantity,(string)$price,2);
                    $price_total_money      = bcadd((string)$price_total_money,(string)$totalPrice,2);

                    //每个商品的运费
                    $freight_total_money    = bcadd((string)$freight_total_money,(string)$item['freight'],2);

                    //获取商品优惠金额
                    $total_discountMoney = bcadd((string)$item['discountMoney']??0.00, (string)$total_discountMoney,2);

                    //商品税率
                    $tax_rate           = isset($currentSupplier['taxRate']) ? $currentSupplier['taxRate'] : '0.00';
                    $goodsTax           = isset($item['goodsTax'])? $item['goodsTax'] : '0.00';
                    $taxFee             = bcmul((string)$quantity, (string)$goodsTax,2);

                    //组装扣除库存数据，自建仓才进行扣除库存
                    $isDeductStock      = false;
                    
                    //自建仓或者需要扣除库存的锁仓商品 (云仓 0.9.34新版 下单后要扣减云仓的代发库存)
//                    if( $canModifyStock == 1 || $currentSupplier['StockRemainNumber'] > 0 ) {
                    //前置仓商品 如果库存为0就不扣除库存
                    if (($fastDeliveryType != 1 || $currentSupplier['number'] > 0) && !in_array($order_type,[9,10])) {
                        $stockDeductInfo[]  = [
                            'SkuID'                 => $currentSupplier['SkuID'],
                            'warehouseID'           => (string)$currentSupplier['warehouseID'],
                            'stockInfoID'           => (string)$currentSupplier['stockInfoID'],
                            'goodsName'             => $currentSupplier['GoodsName'],
                            'number'                => (int)(bcmul((string)$quantity, (string)$goodsSpecNum,2))
                        ];
                    }

//                    }

                    $Images = @json_decode($currentSupplier['Images'],true);
                    $Images = QueryGoodsMicService::instance()->getResetImagesList($Images);
                    //订单商品
                    $orderGoods[] = [
                        'id'                    => IdService::instance()->getOmsID(),
                        'bid'                   => $binfo['bid'],
                        'goods_id'              => $currentSupplier['SkuID'],
                        'name'                  => $currentSupplier['GoodsName'],
                        'barcode'               => $currentSupplier['BarCode'],
                        'skucode'               => $currentSupplier['SKUCode'],
                        'image'                 => current($Images),
                        'extra_image'           => current($Images),
                        'price'                 => $price,
                        'quantity'              => $quantity,
                        'spec_num'              => $goodsSpecNum,
                        'spec_name'             => "{$goodsSpecNum}{$currentSupplier['UnitName']}",
                        'total'                 => $totalPrice,
                        'tax'                   => $taxFee,
                        'freight'               => $item['freight'],
                        'costprice'             => $costPrice,
                        'settlement_price'      => $settlement_price,
                        'store_id'              => $currentSupplier['warehouseID'],
                        'batch_no'              => $currentSupplier['batchNo'],
                        'stock_id'              => $currentSupplier['stockInfoID']
                    ];
                }
            }
        }

        return Normal::returnCode(Normal::SUC,"OK",[
            'settlement_total_money'    => $settlement_total_money,
            'costprice_total_money'     => $costprice_total_money,
            'price_total_money'         => $price_total_money,
            'freight_total_money'       => $freight_total_money,
            'total_discountMoney'       => $total_discountMoney,
            'order_goods'               => $orderGoods,
            'stockDeductInfo'           => $stockDeductInfo
        ]);
    }

    /**
     * 组装供应商订单数据
     * @param array $binfo
     * @param array $orderGoods
     * @param array $supplierGoods
     */
    public function getSupplierOrderData( $param = [] ,$orderGoodsList = [] )
    {
        $binfo              = $param['binfo'];
        $supplierGoodsInfo  = $param['supplierGoodsInfo'];
        $is_seckill         = $orderGoodsList['seckill_info'];
        $template_info      = $orderGoodsList['template_info'];
        $placeOrderInfo     = $param['order'];
        $supplierGoods      = $supplierGoodsInfo['goodsList'];
        $orderGoods         = $placeOrderInfo['goods'];
        $userGoodsData      = array_column($supplierGoodsInfo['authGoodsList'], null,'skucode');
        $supplier_psn       = $this->getCreateOrderSn($supplierGoodsInfo['supplierCode']);

        //处理订单金额
        $settlement_total_money = $orderGoodsList['settlement_total_money'];
        //商品总成本价
        $costprice_total_money  = $orderGoodsList['costprice_total_money'];
        //商品总金额
        $price_total_money      = $orderGoodsList['price_total_money'];
        //运费
        $freight_total_money    = $orderGoodsList['freight_total_money'];
        //税费
        $freightTax             = $placeOrderInfo['freightTax'] ?? 0.00;
        
        //订单总金额     = 商品总金额 + 运费 + 税费  + 非现金抵扣金额
        $order_money            = bcadd((string)$price_total_money, (string)$freight_total_money,2);
        $order_money            = bcadd((string)$order_money, (string)$freightTax,2);
        
        //优惠金额
        $discountMoney          = $orderGoodsList['total_discountMoney'] ?? 0.00;
        
        //海关实际支付单金额 = 商品含税金额  + 运费 - 非现金抵扣金额
        $real_total_money       = bcsub((string)$order_money,(string)$discountMoney,2);
        
        //发票金额
        $invoiceMoney           = 0;
        //判断是否需要结算
        $settlements            = $this->getIsSettlement($binfo['template'],($placeOrderInfo['order_type'] ?? 0),$supplierGoodsInfo['supplierID'],$binfo['is_router_user']);
        
        
        //获取身份证信息
        $cardInfo = getIdCardInfo($placeOrderInfo['buyerIdCard']);
        $supplierOrder = [
            'id'                        => IdService::instance()->getOmsID(),
            'order_sn'              	=> $placeOrderInfo['orderSn'],
            'supplier_psn'          	=> $placeOrderInfo['supplier_psn'] ?? $supplier_psn,
            'supplier_csn'          	=> $placeOrderInfo['supplier_csn'],
            'supplier_dsn'              => $placeOrderInfo['supplier_dsn'],
            'company_id'                => $supplierGoodsInfo['supplierID'],
            'bid'                   	=> $binfo['bid'],
            'order_type'                => $placeOrderInfo['order_type'] ?? 0,
            'order_trade_type'          => $placeOrderInfo['orderTradeType'] ?? 1,//默认普通订单
            'company_type'              => 1,
            //'channel_id'                => $binfo['channel_id'],				//下游商户渠道ID
            'is_channel'                => $binfo['is_channel'] == 1 ? 1 : 0 ,	//是否是渠道商户（1-是，0-否）
            'store_id'              	=> $supplierGoodsInfo['warehouseID'],			//仓库ID
            'buyer_realname'        	=> $placeOrderInfo['buyerRealName'],			//下单人
            'buyer_phone'           	=> $placeOrderInfo['buyerPhone'],				//下单人电话
            'buyer_idcard'          	=> $placeOrderInfo['buyerIdCard'],				//下单人身份证号
            'buyer_sex'                 => $cardInfo['sex'],//性别
            'buyer_age'                 => $cardInfo['age'],//年龄
            'buyer_id_volid'            => $cardInfo['is_volid'],//是否有效
            'receive_name'          	=> $placeOrderInfo['receiveName'],				//收货人姓名
            'recveive_phone'        	=> $placeOrderInfo['recveivePhone'],			//收货人电话
            'province'              	=> $placeOrderInfo['province'],					//省
            'city'                  	=> $placeOrderInfo['city'],						//市
            'district'              	=> $placeOrderInfo['district'],					//区
            'receive_address'       	=> $placeOrderInfo['receiveAddress'],			//收货地址
            'order_money'           	=> $order_money,		                        //订单金额
            'goods_money'           	=> $price_total_money,                          //商品金额
            'deliver_money'         	=> $freight_total_money,                        //运费金额
            'discount_money'        	=> $discountMoney,                             //优惠金额
            'total_money'           	=> $order_money,                               //订单金额
            'invoice_money'         	=> $invoiceMoney,                              //发票金额
            'real_total_money'      	=> $real_total_money,                          //实付金额
            'costprice'                 => $costprice_total_money,                      //供应商成本价
            'settlement_total_money'    => $settlement_total_money,                     //商户结算价格
            'order_remark'          	=> $placeOrderInfo['orderRemarks'],             //订单备注
            'order_source'              => $placeOrderInfo['orderSource'],              //订单来源
            'origin_order_id'           => $placeOrderInfo['originOrderId']??0,              //原始订单id
            'origin_supplier_dsn'       => $placeOrderInfo['originSupplierDsn']??0,              //原始订单号
            'is_split_order'            => $placeOrderInfo['isSplitOrder']??0,              //是否拆单
            'tax'                   	=> $freightTax,                              	//订单总税费
            'cd'                    	=> time(),
            'is_order_declare'          => isset($placeOrderInfo['isOrderDeclare']) && $placeOrderInfo['isOrderDeclare'] == 1 ? 1 : 0 ,
            'is_pay_declare'            => isset($placeOrderInfo['isPayDeclare']) && $placeOrderInfo['isPayDeclare'] == 1 ? 1 : 0  ,
            'is_child_system'           => isset($placeOrderInfo['isChildSystem']) && $placeOrderInfo['isChildSystem'] == 1 ? $placeOrderInfo['isChildSystem'] : 0,//是否是子系统的订单（1-是，0-否）
            'is_top_system'             => isset($placeOrderInfo['isNotTopSystem']) && $placeOrderInfo['isNotTopSystem'] == 0 ? 0 : 1,//是否属于最后一级云仓
            'is_query_express'          => isset($placeOrderInfo['isQueryExpress']) && $placeOrderInfo['isQueryExpress'] == 1 ? 1 : 0,
            'total_template_delivery'   => $orderGoodsList['total_template_delivery'],//总的模板运费
            'delivery_template_info'    => json_encode($template_info, JSON_UNESCAPED_UNICODE),//地区运费模板
            'is_seckill'                => !empty($is_seckill) ? 1 : 0, //是否有参与秒杀的订单
            'is_supplier_settlement'    => $settlements['is_supplier_settlement'],
            'is_channel_settlement'     => $settlements['is_channel_settlement'],
            'is_encrypt_order'          => isset($placeOrderInfo['extends']['isEncryptOrder']) && $placeOrderInfo['extends']['isEncryptOrder'] == 1 ? 1 : 0,//是否是京东加密订单
        ];

        return $supplierOrder;
    }

    /**
     * 组装供应商订单数据
     * @param array $binfo
     * @param array $orderGoods
     * @param array $supplierGoods
     */
    public function getOrderGoodsData( $param = [] )
    {
        $binfo              = $param['binfo'];
        $orderGoods         = $param['order']['goods'];
        $supplierGoodsInfo  = $param['supplierGoodsInfo'];
        $authGoodsList      = $supplierGoodsInfo['authGoodsList'];
        $bestGoodsList      = $supplierGoodsInfo['goodsList'];
        $canModifyStock     = $supplierGoodsInfo['canModifyStock'];
        $userGoodsData      = array_column($authGoodsList, null,'skucode');
        $bestGoodsList      = array_column($bestGoodsList, null,'skuCode');
        $settlement_total_money = $costprice_total_money = $price_total_money = $freight_total_money = $total_discountMoney = 0 ;
        $hasDiscountMoney  = $hasDiscountPonitsMoney = $hasDiscountRedEnvelopeMoney = $hasDiscountActivityMoney = $hasDiscountCouponMoney = $hasDiscountPayWayMoney = 0;
        $orderItemsList = [];
        $total_template_delivery = '0';//该订单总的模板运费
        $totalWeight             = 0; //该订单下所有商品的总重量
        $suppplierOrderGoods     = []; //商品
        $currentOrderTemplateList = [];//当前子订单商品组的商品模板
        //判断是否有秒杀
        $seckill_info = [];
        //判断是否需要包邮计算运费
        $isNoFreeShipping = [] ;
        //组装每个子订单的商品
       
        foreach ($orderGoods as $item )
        {

            $skucode                = $item['goodsSku'];
            $quantity               = $item['goodsNum'];
            $price                  = $item['goodsPrice'];
            $goodsSpecNum           = $item['goodsSpecNum'];
            if( !isset($bestGoodsList[$skucode]) ) {
                return Normal::returnCode(Normal::FAIL,"当前SKU：{$skucode} 商品已下架,请重新选择商品进行下单!(100007)");
            }

            //获取原始商品快照
            $currentSupplier        = $bestGoodsList[$skucode];
            //当前供应商规格组
            $specList = array_column($currentSupplier['SpecList'],null,'SpecificationNum');
            if( !isset($specList[$goodsSpecNum]) ) {
                return Normal::returnCode(Normal::FAIL,"当前SKU：{$skucode}，规格：{$currentSupplier['batchNo']}，商品已下架,请重新选择商品进行下单!(100008)");
            }

            //获取授权商品快照
            $userGoods              = $userGoodsData[$skucode];
            $spec_list              = @json_decode($userGoods['spec_list'],true);
            $spec_list              = array_column($spec_list, null,'spec_num');
            if( !isset($spec_list[$goodsSpecNum]) ) {
                return Normal::returnCode(Normal::FAIL,"当前SKU：{$skucode}，规格：{$currentSupplier['batchNo']}，商品已下架,请重新选择商品进行下单!(100009)");
            }

            //结算价
            $settlement_price = $spec_list[$goodsSpecNum]['priceSettlement'];
            //成本价
            $costPrice        = $specList[$goodsSpecNum]['SpecificationPrice'];
            //包邮成本价
            $costHasPostPrice = $specList[$goodsSpecNum]['SpecificationFreightPrice']??$specList[$goodsSpecNum]['SpecificationPrice'];
            //规格名称
            $spec_name        = $goodsSpecNum . $currentSupplier['UnitName'];

            $settlement_total_money = bcadd((string)$settlement_total_money, bcmul((string)$quantity,(string)$settlement_price,2),2);
            $costprice_total_money  = bcadd((string)$costprice_total_money, bcmul((string)$quantity,(string)$costPrice,2),2);
            $totalPrice             = bcmul((string)$quantity,(string)$price,2);
            $price_total_money      = bcadd((string)$price_total_money,(string)$totalPrice,2);

            //每个商品的运费
            $freight_total_money    = bcadd((string)$freight_total_money,(string)$item['freight'],2);

            //商品税率
            $tax_rate           = isset($currentSupplier['taxRate']) ? $currentSupplier['taxRate'] : '0.00';
            $goodsTax           = isset($item['goodsTax'])? $item['goodsTax'] : '0.00';
            $taxFee             = bcmul((string)$quantity, (string)$goodsTax,2);
            //计算单价  假如单价 大于等于 高消费税预警金额 时 其税率就改为 高消费税率
            $hightRatePriceData = [
                'price'              => $price,
                'goodsSpecNum'       => $goodsSpecNum,
                'conSumptionTaxRate' => $currentSupplier['conSumptionTaxRate'],
                'conSumptionPrice'   => $currentSupplier['conSumptionPrice'],
                'tax_rate'           => $tax_rate,
                'has_rate'           => $currentSupplier['isHaveTaxRate']
            ];
            $hightRatePriceRes = SupplierCommodityPriceService::instance()->handleHightRatePrice($hightRatePriceData);
            $tax_rate = $hightRatePriceRes['tax_rate'];

            //获取商品优惠金额
            $total_discountMoney            = bcadd((string)($item['discountMoney']??'0.00'), (string)$total_discountMoney,2);
            $hasDiscountPonitsMoney         = bcadd((string)($item['discountPointMoney']??'0.00'), (string)$hasDiscountPonitsMoney,2);
            $hasDiscountRedEnvelopeMoney    = bcadd((string)($item['discountRedEnvelopeMoney']??'0.00'), (string)$hasDiscountRedEnvelopeMoney,2);
            $hasDiscountActivityMoney       = bcadd((string)($item['discountActivityMoney']??'0.00'), (string)$hasDiscountActivityMoney,2);
            $hasDiscountCouponMoney         = bcadd((string)($item['discountCouponMoney']??'0.00'), (string)$hasDiscountCouponMoney,2);
            $hasDiscountPayWayMoney         = bcadd((string)($item['discountPaywayMoney']??'0.00'), (string)$hasDiscountPayWayMoney,2);
            
            //组装返回数据格式
            $goodsItemId = IdService::instance()->getOmsID();
            $orderItemsList[] = [
                'goodsItemId'   => (string)$goodsItemId,
                'goodsBatchNo'  => (string)$currentSupplier['batchNo'],
                'goodsSku'      => (string)$skucode,
                'goodsNum'      => (string)$quantity,
                'goodsPrice'    => (string)$price,
                'goodsSpecNum'  => (string)$goodsSpecNum,
                'startExpDate'  => (string)($item['startExpDate'] ??''),
                'endExpDate'    => (string)($item['endExpDate'] ??'')
            ];

            $isSettingFreight = 0;
            //获取运费模板ID
            if( isset($currentSupplier['freightTemplateID']) && $currentSupplier['freightTemplateID'] > 0 ) {
                $currentOrderTemplateList[] = $currentSupplier['freightTemplateID'];
                $isSettingFreight = 1;
            }

            //是否包邮字段
            $IsFreeShipping = isset($currentSupplier['isFreeShipping']) && $currentSupplier['isFreeShipping'] == 1 ? 1 : 0 ;

            //是否需要扣除库存标识
            if ($canModifyStock== 1 || $currentSupplier['StockRemainNumber'] > 0){
                $is_deduct_stock = 1;
            }else{
                $is_deduct_stock = 0;
            }
           
            $weight            = $currentSupplier['weight'] ?? 0;//重量单位g 默认0
            if(!$IsFreeShipping ) {
                $totalWeight   += $weight * $item['goodsNum'] * $item['goodsSpecNum'];
                $isNoFreeShipping[] = 1;
            }

            $Images = @json_decode($currentSupplier['Images'],true);
            $Images = QueryGoodsMicService::instance()->getResetImagesList($Images);

            //判断运费模板
            if ($currentSupplier['IsSettingFreightTemplate']){
                $freight_template=$currentSupplier['SupplierFreightTemplate'];
            }else{
                $freight_template=$currentSupplier['FreightTemplate'];
            }
            
            $suppplierOrderGoods[] = [
                'id'                        => $goodsItemId,
                'bid'                       => $binfo['bid'],
                'goods_id'                  => $currentSupplier['SkuID'],
                'goods_name'                => $currentSupplier['GoodsName'],
                'barcode'                   => $currentSupplier['BarCode'],
                'skucode'                   => $currentSupplier['SKUCode'],
                'supplier_skuid'            => $currentSupplier['supplierSKUID'],
                'supplier_skucode'          => $currentSupplier['supplierSKUCode'],
                'supplier_store_code'       => $currentSupplier['declarePlanCode'],  //供应商仓库编码
                'supplier_store_id'         => $currentSupplier['defaultStock'],  //供应商仓库ID
                'supplier_goods_type'       => $currentSupplier['deliveryMethod'],  //供应商商品类型
                'supplier_store_parameters' => $currentSupplier['JsonBody'],//仓库订单商品额外仓库数据
                'is_supplier_combine_skuid' => $currentSupplier['IsCombineSupplierCommodity'],  //是否是组合装商品（1-是，0-否）
                'goods_type'                => $currentSupplier['supplierCommodityType'],
                'image'                     => current($Images),
                'quantity'                  => $quantity,
                'spec_num'                  => $goodsSpecNum,
                'spec_name'                 => $spec_name,
                'weight'                    => $weight,                         //重量单位g
                'total'                     => $totalPrice,                 	//商品总价
                'price'                     => $price,							//商品单价
                'costprice'                 => $costPrice,             	        //供应商成本价
                'tax'                       => $taxFee,                         //单商品总税费
                'tax_rate'                  => $tax_rate,                       //商品税率
                'has_rate'                  => $currentSupplier['isHaveTaxRate'],//是否含税
                'channel_has_rate'          => $binfo['user_tax_mode'], //是否用户设置含税
                'is_free_postfee'           => $IsFreeShipping,//是否包邮
                'freight'                   => $item['freight'],                //商品运费
                'discount_money'                => $item['discountMoney'] ?? '0.00',//商品总优惠金额
                'discount_point_money'          => $item['discountPointMoney'] ?? '0.00',//商品积分优惠金额
                'discount_red_envelope_money'   => $item['discountRedEnvelopeMoney'] ?? '0.00',//商品红包优惠金额
                'discount_activity_money'       => $item['discountActivityMoney'] ?? '0.00', //商品活动优惠金额
                'discount_coupon_money'         => $item['discountCouponMoney'] ?? '0.00',//商品优惠卡券金额
                'discount_payway_money'         => $item['discountPaywayMoney'] ?? '0.00',//商品支付方式优惠金额
                'settlement_price'          => $settlement_price,               //商户结算价格
                'store_id'                  => $currentSupplier['warehouseID'], //仓库ID
                'batch_no'                  => $currentSupplier['batchNo'],	    //批次号
                'stock_id'                  => $currentSupplier['stockInfoID'], //库存ID
                'cd'                        => time(),							//创建时间
                'declare_skucode'           => $currentSupplier['DeclareDeclareSKUCode'],
                'declare_goods_name'        => $currentSupplier['DeclareDeclareCommodityName'],
                'declare_spec'              => $currentSupplier['DeclareSpecifications'],
                'declare_desc'              => $currentSupplier['DeclareFunction'],
                'declare_barcode'           => $currentSupplier['DeclareDeclareBarCode'],
                'declare_unit'              => $currentSupplier['DeclareMeasurementUnit'],
                'declare_unit_code'         => $currentSupplier['DeclareMeasurementUnitCode'],
                'declare_currency'          => $currentSupplier['DeclareCurrency'],
                'declare_currency_code'     => $currentSupplier['DeclareCurrencyCode'],
                'declare_country'           => $currentSupplier['DeclareCountry'],
                'declare_country_code'      => $currentSupplier['DeclareCountryCode'],
                'declare_hscode'            => $currentSupplier['hsCode'],
                'ebc_name'                  => $currentSupplier['enterpriseName'],
                'ebc_code'                  => $currentSupplier['enterpriseCode'],
                'is_deduct_stock'           => $is_deduct_stock,
                'is_seckill'                => !empty($item['seckill_info']) ? 1 : 0 ,
                'is_seckill_info'           => $item['seckill_info'] ?? '',
                'is_setting_freight'        => $isSettingFreight,
                'is_insurance'              => $currentSupplier['IsInsurance'],
                'insurance_day'             => $currentSupplier['InsurancePriceDay'],
                'freight_template'          => $currentSupplier['freightTemplateID'],
                'cost_post_fee'             => bcsub($costHasPostPrice,$costPrice,2),
                'is_hight_rate'             => $hightRatePriceRes['is_hight_rate'],
                'high_rate_warnning_price'  => $hightRatePriceRes['warnningPrice'],
                'lower_rate'                => $hightRatePriceRes['lower_rate'],
            ];
            if( isset($item['seckill_info']) && !empty($item['seckill_info'])) {
                $seckill_info[] = [
                    'goods_id'      => $currentSupplier['SkuID'],
                    'goods_num'     => $quantity,
                    'goods_name'    => $currentSupplier['GoodsName'],
                    'skucode'       => $skucode,
                    'barcode'       => $currentSupplier['BarCode'],
                    'seckill_info'  => $item['seckill_info']
                ];
            }
        }
        return Normal::returnCode(Normal::SUC,"OK",[
            'settlement_total_money'    => $settlement_total_money,
            'costprice_total_money'     => $costprice_total_money,
            'price_total_money'         => $price_total_money,
            'freight_total_money'       => $freight_total_money,
            'order_goods'               => $suppplierOrderGoods,
            'orderItemsList'            => $orderItemsList,
            'totalWeight'               => $totalWeight,
            'isNoFreeShipping'          => $isNoFreeShipping,
            'total_discountMoney'       => $total_discountMoney,
            'discount_points_money'         => $hasDiscountPonitsMoney,
            'discount_red_envelope_money'   => $hasDiscountRedEnvelopeMoney,
            'discount_activity_money'       => $hasDiscountActivityMoney,
            'discount_coupon_money'         => $hasDiscountCouponMoney,
            'discount_payway_money'         => $hasDiscountPayWayMoney,
            'seckill_info'              => $seckill_info,
            'currentOrderTemplateList'  => $currentOrderTemplateList,
        ]);
    }

    /**
     * 订单申报推送服务
     * @param array $param
     */
    public function orderPush( $param = [] )
    {
        $param['orderDeclare'] = [
            'order_decalre_status'  => 2,
            'order_decalre_result'  => '订单预处理成功',
        ];

        $res = OrderDeclare::instance()->orderDecalreNotify($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }

        $res = OrderDeclareServiceApiClient::instance()->OrderApply($param);
        if( $res['code'] != Normal::SUC ) {
            $param['orderDeclare'] = [
                'order_decalre_status'  => 3,
                'order_decalre_result'  => $res['msg'],
            ];
            $result = OrderDeclare::instance()->orderDecalreNotify($param);
            if($result['code'] != Normal::SUC){
                return $result;
            }
            return $res;
        }

        return Normal::returnCode(Normal::SUC,"订单申报推送成功");
    }
    
    /**
     * 根据优选规则获取是否需要结算
     */
    public function getIsSettlement($template_json,$order_type,$company_id,$is_router_user)
    {
        $is_supplier_settlement = 1;
        $is_channel_settlement  = 1;
        //非第三方订单
        if ($order_type != 0 ){
            $is_channel_settlement=0;
        }else{
            $template=@json_decode($template_json,true);
            if (isset($template['GoodsAdvanceSettings']['SupplierChoice'])){
                $SupplierChoice=$template['GoodsAdvanceSettings']['SupplierChoice'];
                if ($template['GoodsSettingMode']== 2 && $SupplierChoice['mode'] == 2 && $SupplierChoice['SupplierChoiceMode']==1 ){
                    $supplierCompanyMap=array_column($SupplierChoice['SupplierList'],NULL,'SupplierCompanyID');
                    if (isset($supplierCompanyMap[$company_id]) && isset($supplierCompanyMap[$company_id]['IsSettlement'])){
                        $is_channel_settlement = $supplierCompanyMap[$company_id]['IsSettlement'];
                    }
                }
            }
        }
        return [
            'is_supplier_settlement' => $is_router_user==1?0:$is_supplier_settlement,
            'is_channel_settlement'  => $is_channel_settlement
        ];
    } 
    /**
     * 获取待审核订单数
     */
    public function getOrderAfterSaleCount()
    {
        $count = 0 ;
        $count =  self::query()
        ->where([
            ['after_verify_status','=',0],
            ['after_sale_status','=',1]
        ])->count();
        return Normal::returnCode(Normal::SUC,"请求成功",array("count" => $count));
    }
}
